import React, { useState, useEffect } from 'react';
import { useNavigate } from 'react-router-dom';
import { getProductList, updateProductStatus, deleteProduct } from '../../api/shop';
import { 
  Input, 
  Button, 
  Table, 
  Space, 
  Image, 
  Tag, 
  message,
  Card,
  Row,
  Col,
  Pagination,
  Modal,
  Form
} from 'antd';
import { 
  SearchOutlined, 
  PlusOutlined, 
  EditOutlined, 
  UpOutlined, 
  DownOutlined,
  DeleteOutlined
} from '@ant-design/icons';
import type { ColumnsType } from 'antd/es/table';
import CommodityEditForm from '../../components/CommodityEditForm';

// 商品数据类型
interface ProductType {
  id: number;
  product_name: string;
  product_code: string;
  category_id: number;
  category_name: string;
  product_tags: string;
  store_id: number;
  sale_status: number;
  sales_type: number;
  product_price: number;
  base_price: number;
  cost_price: number;
  support_life_points: number;
  attachments: string;
  delisting_reason: string;
  listing_reason: string;
  stock_quantity: number;
  sales_price: number;
  created_at: string;
  updated_at: string;
  skus: SkuType[];
}

// SKU数据类型
interface SkuType {
  id: number;
  product_id: number;
  sku_name: string;
  sku_price: number;
  strikethrough_price: number;
  sku_image_path: string;
  stock: number;
  spec_json: string;
  spec_type: string;
  cost_price: number;
  stock_warning_threshold: number;
  stock_status: number;
  created_at: string;
  updated_at: string;
}

// 分页数据类型
interface PaginationType {
  current_page: number;
  page_size: number;
  total: number;
  total_pages: number;
  has_prev: boolean;
  has_next: boolean;
  prev_page: number;
  next_page: number;
}

const Commodity: React.FC = () => {
  const navigate = useNavigate();
  const [searchText, setSearchText] = useState('');
  const [statusFilter, setStatusFilter] = useState<number>(1);
  const [loading, setLoading] = useState(false);
  const [productList, setProductList] = useState<ProductType[]>([]);
  const [pagination, setPagination] = useState<PaginationType>({
    current_page: 1,
    page_size: 10,
    total: 0,
    total_pages: 0,
    has_prev: false,
    has_next: false,
    prev_page: 0,
    next_page: 0
  });
  const [statusModalVisible, setStatusModalVisible] = useState(false);
  const [currentProduct, setCurrentProduct] = useState<ProductType | null>(null);
  const [statusForm] = Form.useForm();
  
  // 编辑弹窗相关状态
  const [editModalVisible, setEditModalVisible] = useState(false);
  const [editingProduct, setEditingProduct] = useState<ProductType | null>(null);

  // 获取商品列表
  const fetchProductList = async (page: number = 1, keyword: string = '', sale_status: number = 1) => {
    setLoading(true);
    try {
      const params: any = {
        page,
        page_size: pagination.page_size,
        keyword
      };
      
      // 传递sale_status参数
      params.sale_status = sale_status;
      
      console.log('API请求参数:', params);
      const response = await getProductList(params);
      
      console.log('商品列表响应:', response);
      
      if (response) {
        setProductList(response.list);
        setPagination(response.pagination);
      }
    } catch (error) {
      console.error('获取商品列表失败:', error);
      message.error('获取商品列表失败');
    } finally {
      setLoading(false);
    }
  };

  // 组件挂载时获取数据
  useEffect(() => {
    fetchProductList();
  }, []);

  // 处理搜索
  const handleSearch = () => {
    fetchProductList(1, searchText, statusFilter);
  };

  // 处理状态筛选
  const handleStatusFilter = (status: number) => {
    setStatusFilter(status);
    fetchProductList(1, searchText, status);
  };

  // 处理编辑
  const handleEdit = (record: ProductType) => {
    setEditingProduct(record);
    setEditModalVisible(true);
  };

  // 处理编辑弹窗关闭
  const handleEditModalClose = () => {
    setEditModalVisible(false);
    setEditingProduct(null);
  };

  // 处理编辑成功
  const handleEditSuccess = () => {
    setEditModalVisible(false);
    setEditingProduct(null);
    // 刷新商品列表
    fetchProductList(pagination.current_page, searchText, statusFilter);
    message.success('商品更新成功！');
  };

  // 处理状态切换
  const handleToggleStatus = (record: ProductType) => {
    setCurrentProduct(record);
    setStatusModalVisible(true);
    statusForm.setFieldsValue({
      sale_status: record.sale_status === 1 ? 2 : 1,
      reason: ''
    });
  };

  // 确认状态变更
  const handleStatusChange = async () => {
    try {
      const values = await statusForm.validateFields();
      if (!currentProduct) return;

      const response = await updateProductStatus(currentProduct.id, {
        sale_status: values.sale_status,
        reason: values.reason
      });

      console.log('状态变更响应:', response);
      message.success('商品状态更新成功');
      setStatusModalVisible(false);
      statusForm.resetFields();
      
      // 刷新当前页数据
      fetchProductList(pagination.current_page, searchText, statusFilter);
    } catch (error) {
      console.error('状态变更失败:', error);
      message.error('状态变更失败，请重试');
    }
  };

  // 处理添加商品
  const handleAddProduct = () => {
    navigate('/shop/commodity/edit');
  };

  // 处理删除商品
  const handleDelete = async (record: ProductType) => {
    Modal.confirm({
      title: '确认删除',
      content: `确定要删除商品"${record.product_name}"吗？此操作不可恢复。`,
      okText: '删除',
      okType: 'danger',
      cancelText: '取消',
      onOk: async () => {
        try {
          console.log('删除商品:', record.id);
          const response = await deleteProduct(record.id);
          console.log('删除响应:', response);
          message.success('商品删除成功');
          
          // 刷新当前页数据
          fetchProductList(pagination.current_page, searchText, statusFilter);
        } catch (error) {
          console.error('删除商品失败:', error);
          message.error('删除商品失败，请重试');
        }
      }
    });
  };

  // 处理分页变化
  const handlePageChange = (page: number, pageSize?: number) => {
    const newPageSize = pageSize || pagination.page_size;
    setPagination(prev => ({ ...prev, page_size: newPageSize }));
    fetchProductList(page, searchText, statusFilter);
  };

  // 表格列配置
  const columns: ColumnsType<ProductType> = [
    {
      title: '产品名称',
      dataIndex: 'product_name',
      key: 'product_name',
      width: 200,
      render: (text, record) => (
        <Space>
          <Image
            width={40}
            height={40}
            src={record.attachments ? (() => {
              try {
                const attachments = JSON.parse(record.attachments);
                return attachments && attachments.length > 0 && attachments[0]?.url ? attachments[0].url : 'https://via.placeholder.com/40x40';
              } catch (error) {
                console.error('解析attachments失败:', error);
                return 'https://via.placeholder.com/40x40';
              }
            })() : 'https://via.placeholder.com/40x40'}
            alt={text}
            style={{ borderRadius: '4px' }}
          />
          <div>
            <div style={{ fontWeight: 'bold' }}>{text}</div>
            <div style={{ fontSize: '12px', color: '#666' }}>{record.product_code}</div>
          </div>
        </Space>
      ),
    },
    {
      title: '分类',
      dataIndex: 'category_name',
      key: 'category_name',
      width: 120,
    },
    {
      title: 'SKU规格',
      dataIndex: 'skus',
      key: 'skus',
      width: 200,
      render: (skus: SkuType[]) => {
        if (!skus || !Array.isArray(skus)) {
          return <div style={{ fontSize: '12px', color: '#999' }}>暂无规格</div>;
        }
        
        return (
          <div>
            {skus.slice(0, 2).map((sku, index) => (
              <div key={index} style={{ fontSize: '12px', color: '#666', lineHeight: '1.4' }}>
                {sku.sku_name} - ¥{(sku.sku_price / 100).toFixed(2)}
              </div>
            ))}
            {skus.length > 2 && (
              <div style={{ fontSize: '12px', color: '#999' }}>
                +{skus.length - 2} 个规格
              </div>
            )}
          </div>
        );
      },
    },
    {
      title: '价格',
      dataIndex: 'sales_price',
      key: 'sales_price',
      width: 100,
      render: (price: number) => (
        <span style={{ color: '#ff4d4f', fontWeight: 'bold' }}>
          ¥{(price / 100).toFixed(2)}
        </span>
      ),
    },
    {
      title: '库存',
      dataIndex: 'stock_quantity',
      key: 'stock_quantity',
      width: 80,
      render: (stock: number) => (
        <Tag color={stock > 100 ? 'green' : stock > 50 ? 'orange' : 'red'}>
          {stock}
        </Tag>
      ),
    },
    {
      title: '状态',
      dataIndex: 'sale_status',
      key: 'sale_status',
      width: 80,
      render: (status: number) => (
        <Tag color={status === 1 ? 'green' : 'red'}>
          {status === 1 ? '在售' : status === 2 ? '下架' : '未知'}
        </Tag>
      ),
    },
    {
      title: '创建时间',
      dataIndex: 'created_at',
      key: 'created_at',
      width: 150,
      render: (time: string) => new Date(time).toLocaleString(),
    },
    {
      title: '操作',
      key: 'action',
      width: 160,
      render: (_, record) => (
        <Space size="small">
          <Button
            type="text"
            icon={<EditOutlined />}
            onClick={() => handleEdit(record)}
            title="编辑"
          />
          <Button
            type="text"
            icon={record.sale_status === 1 ? <DownOutlined /> : <UpOutlined />}
            onClick={() => handleToggleStatus(record)}
            title={record.sale_status === 1 ? '下架' : '上架'}
            style={{ color: record.sale_status === 1 ? '#ff4d4f' : '#52c41a' }}
          />
          <Button
            type="text"
            danger
            icon={<DeleteOutlined />}
            onClick={() => handleDelete(record)}
            title="删除"
          />
        </Space>
      ),
    },
  ];

  return (
    <div style={{ padding: '24px', background: '#f5f5f5', minHeight: '100vh' }}>
      <Card style={{ borderRadius: '8px' }}>
        {/* 顶部搜索和按钮区域 */}
        <Row justify="space-between" align="middle" style={{ marginBottom: '16px' }}>
          <Col>
            <Space>
              <span style={{ fontSize: '16px', fontWeight: 'bold' }}>商品列表</span>
              <Input
                placeholder="搜索商品名称或编号"
                prefix={<SearchOutlined />}
                value={searchText}
                onChange={(e) => setSearchText(e.target.value)}
                onPressEnter={handleSearch}
                style={{ width: 300 }}
                allowClear
              />
              <Button type="primary" onClick={handleSearch}>
                搜索
              </Button>
            </Space>
          </Col>
          <Col>
            <Button
              type="primary"
              icon={<PlusOutlined />}
              onClick={handleAddProduct}
              style={{ borderRadius: '6px' }}
            >
              新上商品
            </Button>
          </Col>
        </Row>

        {/* 筛选按钮区域 */}
        <div style={{ marginBottom: '16px' }}>
          <Space>
            <Button
              type={statusFilter === 1 ? 'primary' : 'default'}
              onClick={() => handleStatusFilter(1)}
              style={{ borderRadius: '6px' }}
            >
              在售
            </Button>
            <Button
              type={statusFilter === 2 ? 'primary' : 'default'}
              onClick={() => handleStatusFilter(2)}
              style={{ borderRadius: '6px' }}
            >
              下架
            </Button>
          </Space>
        </div>

        {/* 表格区域 */}
        <Table
          columns={columns}
          dataSource={productList}
          loading={loading}
          pagination={false}
          scroll={{ x: 1200 }}
          rowKey="id"
        />

        {/* 分页组件 */}
        <div style={{ marginTop: '16px', textAlign: 'right' }}>
          <Pagination
            current={pagination.current_page}
            total={pagination.total}
            pageSize={pagination.page_size}
            showSizeChanger
            showQuickJumper
            showTotal={(total, range) => `第 ${range[0]}-${range[1]} 条/共 ${total} 条`}
            onChange={handlePageChange}
            onShowSizeChange={handlePageChange}
            pageSizeOptions={['10', '20', '50', '100']}
            style={{ justifyContent: 'flex-end' }}
          />
        </div>
      </Card>

      {/* 状态变更模态框 */}
      <Modal
        title="商品状态变更"
        open={statusModalVisible}
        onOk={handleStatusChange}
        onCancel={() => {
          setStatusModalVisible(false);
          statusForm.resetFields();
        }}
        okText="确认"
        cancelText="取消"
      >
        <Form form={statusForm} layout="vertical">
          <Form.Item
            name="sale_status"
            label="目标状态"
            rules={[{ required: true, message: '请选择目标状态' }]}
          >
            <Input 
              disabled 
              value={statusForm.getFieldValue('sale_status') === 1 ? '在售' : '下架'}
            />
          </Form.Item>
          <Form.Item
            name="reason"
            label="变更原因"
            rules={[{ required: true, message: '请输入变更原因' }]}
          >
            <Input.TextArea
              rows={3}
              placeholder="请输入状态变更原因"
              maxLength={200}
              showCount
            />
          </Form.Item>
        </Form>
      </Modal>

      {/* 编辑商品弹窗 */}
      <Modal
        title="编辑商品"
        open={editModalVisible}
        onCancel={handleEditModalClose}
        footer={null}
        width={1200}
        style={{ top: 20 }}
      >
        <CommodityEditForm
          visible={editModalVisible}
          onCancel={handleEditModalClose}
          onSuccess={handleEditSuccess}
          isEdit={true}
          productData={editingProduct}
          productId={editingProduct?.id}
        />
      </Modal>
    </div>
  );
};

export default Commodity;